import React, { useEffect, useState } from "react";
import { Button, Cascader, Form, Input, Switch } from "antd";
import type { FormInstance } from "antd/es/form";
import { categoryGet, categoryPost, coursePost } from "@/api/course";
import { CategoryType, CourseType } from "@/types/course";
import TextArea from "antd/es/input/TextArea";
import ImgUpload from "@/components/img-upload";
import RichEditor from "@/components/rich-editor";
import { Auth } from "@/guard/permission";

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const CoursePub: React.FC = () => {
  const formRef = React.useRef<FormInstance>(null);
  const [cateList, setCateList] = useState<CategoryType[]>([]);
  const onFinish = (values: CourseType) => {
    console.log(values);
    values.cateLv1 = values.category[0];
    values.cateLv2 = values.category[1];
    coursePost(values);
  };

  const onReset = () => {
    formRef.current?.resetFields();
  };

  useEffect(() => {
    categoryGet(true).then((res) => {
      let results: CategoryType[] = res.data.results;
      let parentArr = results.filter((item) => item.parentId == "0-0");
      parentArr.forEach((item) => {
        let children = results.filter(
          (child) => item.objectId == child.parentId
        );
        if (children.length) {
          item.children = children;
        }
      });
      setCateList(parentArr);
    });
  }, []);
  const initData = {
    name: "前端开发React",
    intro: "React+Typescript项目开发",
  };
  let Btn = Auth(
    <Button type="primary" htmlType="submit">
      确定
    </Button>,
    ["超级管理员"]
  );
  return (
    <Form
      {...layout}
      ref={formRef}
      name="control-ref"
      onFinish={onFinish}
      initialValues={initData}
    >
      <Form.Item name="name" label="分类名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="poster" label="课程封面" rules={[{ required: true }]}>
        <ImgUpload />
      </Form.Item>
      <Form.Item name="category" label="课程分类" rules={[{ required: true }]}>
        <Cascader
          options={cateList}
          fieldNames={{ label: "name", value: "name" }}
          placeholder="请选择课程分类"
        />
      </Form.Item>
      <Form.Item
        label="是否上架"
        name="isvip"
        valuePropName="checked"
        rules={[{ required: true }]}
      >
        <Switch />
      </Form.Item>
      <Form.Item name="intro" label="课程简介" rules={[{ required: true }]}>
        <TextArea />
      </Form.Item>
      <Form.Item name="content" label="课程详情" rules={[{ required: true }]}>
        <RichEditor />
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Btn />
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
      </Form.Item>
    </Form>
  );
};

export default CoursePub;
